package com.settlement.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.result.Result;
import com.settlement.system.model.dto.FileInfo;
import com.settlement.system.service.OssService;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Tag(name = "文件接口")
@RestController
@RequestMapping("/api/v1/files")
@RequiredArgsConstructor
public class FileController {

    private final OssService ossService;

    @PostMapping
    @Operation(summary = "文件上传", security = {@SecurityRequirement(name = "Authorization")})
    public Result<FileInfo> uploadFile(
            @Parameter(description ="表单文件对象") @RequestParam(value = "file") MultipartFile file
    ) {
        FileInfo fileInfo = ossService.uploadFile(file);
        return Result.success(fileInfo);
    }

    @DeleteMapping
    @Operation(summary = "文件删除", security = {@SecurityRequirement(name = "Authorization")})
    @SneakyThrows
    public Result<?> deleteFile(
            @Parameter(description ="文件路径") @RequestParam String filePath
    ) {
        boolean result = ossService.deleteFile(filePath);
        return Result.judge(result);
    }

    @Operation(summary = "下载文件")
    @PreventDuplicateSubmit
    @GetMapping("/downloadFile/{logId}")
    public void downloadFile(@PathVariable Long logId, HttpServletResponse response) throws Exception{
        // 清空response
        /*response.reset();
        // 设置response的Header
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(operateLog.getFileName(), StandardCharsets.UTF_8));
        // 告知浏览器文件的大小
        response.addHeader("Content-Length", operateLog.getFileData().length + "");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        outputStream.write(operateLog.getFileData());
        outputStream.flush();
        outputStream.close();*/
    }
}
